import pandas as pd
import os
import time


def finone(dfi, col, date = '', offset = 0) :
    if dfi is None or col not in dfi:
        return None

    dataType = str(dfi[col].dtype)
    if dataType != 'int64' and dataType != 'float64':
        col_numeric = col + '_NUMERIC'
        if col_numeric not in dfi:
            dfi[col_numeric] = pd.to_numeric(dfi[col], errors='coerce')
        col = col_numeric
    
    if date == '':
        if offset < len(dfi):
            return dfi[col].iloc[offset]
        return None
    
    if date == 'fixed-last-season':
        date = dfi.iloc[0].name[5:]
    
    pattern = '%s-' + date
    year = time.localtime().tm_year
    while year > 1988:
        idx = pattern % str(year)
        if idx in dfi.index:
            offset -= 1
            if offset < 0:
                val = dfi.loc[idx, col]
                return val
        year -= 1
    
    return None


def financeDataFrame(code) :
    filename = './analyse_data/a/%s.csv' % code
    if not os.path.exists(filename):
        return None
    dfi = pd.read_csv(filename, encoding='ansi')
    dfi.set_index('报告日期', inplace=True)
    return dfi


if __name__ == '__main__' : 
    dfi = financeDataFrame('000002')
    dfi.info()
    # print(finone(dfi, '基本每股收益(元)', '3-31'))
    # print(finone(dfi, '基本每股收益(元)', '12-31'))
    print(finone(dfi, '基本每股收益(元)', 'fixed-last-season'))